package com.yb.bluetooth.util;

import android.content.Intent;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;


public final class ActivityCallUtils extends Fragment {

    private int mRequestCode;
    private static final String FRAGMENT_TAG = "InvisibleFragment";
    private ActivityResultListener mListener;

    private ActivityCallUtils() {
    }

    public static ActivityCallUtils instance(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        Fragment existedFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
        ActivityCallUtils fragment;
        if (existedFragment != null) {
            fragment = (ActivityCallUtils) existedFragment;
        } else {
            fragment = new ActivityCallUtils();
            fragmentManager.beginTransaction()
                    .add(fragment, FRAGMENT_TAG)
                    .commitNow();
        }
        return fragment;
    }

    /**
     * 回调[onActivityResult]结果
     *
     * @param requestCode 请求码
     * @param listener    结果监听
     */
    public void callActivityResult(int requestCode, ActivityResultListener listener) {
        this.mRequestCode = requestCode;
        this.mListener = listener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mRequestCode) {
            mListener.onActivityResult(resultCode, data);
        }
    }

    @FunctionalInterface
    public interface ActivityResultListener {

        void onActivityResult(int resultCode, Intent data);

    }

}
